package com.ucar.umock.client.web;

import com.ucar.umock.client.UMockHelper;
import com.ucar.umock.client.config.UMockMethodConfigBean;
import com.ucar.umock.client.util.UMockFreemarkerUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UMockConfigAction
 * @Description TODO
 * @Author zhanbs baoshan.zhan@ucarinc.com
 * @Date 2020/4/2 17:08
 * @Version 1.0
 **/
@Controller
public class UMockConfigAction {

    @RequestMapping(value = "/umock")
    public void umock(HttpServletResponse response){
        try {
            Collection<UMockMethodConfigBean> allMockList=UMockHelper.getMockMethodConfigOperate().getAllUMockMethodConfig();
            Map<String,List<UMockMethodConfigBean>> umockDataMap=new HashMap<String,List<UMockMethodConfigBean>>();
            for(UMockMethodConfigBean item:allMockList){
                String className=item.getClassName();
                List<UMockMethodConfigBean> itemList=null;
                if(umockDataMap.containsKey(className)){
                    itemList=umockDataMap.get(className);
                }else{
                    itemList=new ArrayList<UMockMethodConfigBean>();
                    umockDataMap.put(className,itemList);
                }
                itemList.add(item);
            }
            Map<String,Object> rootMap=new HashMap<String, Object>();
            rootMap.put("data",umockDataMap);
            String cnt= UMockFreemarkerUtil.parseHtml("com/ucar/umock/client/web/page/umock.html",rootMap);
            response.setCharacterEncoding("UTF-8");
            Writer out=response.getWriter();
            out.write(cnt);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private boolean getSwitch(Integer mark){
        boolean b=false;
        if(mark==null){
            mark=0;
        }
        if(mark==1){
            //开启
            b=true;
        }else{
            b=false;
        }
        return b;
    }
    @RequestMapping(value = "/umockSwitchOperate")
    public String umockSwitchOperate(String key,Integer mark){
        UMockHelper.getMockMethodConfigOperate().updateMockSwitch(key,getSwitch(mark));
        return "redirect:umock";
    }

    @RequestMapping(value = "/umockSwitchOperateByClazz")
    public String umockSwitchOperateByClazz(String clazzName,Integer mark){
        UMockHelper.getMockMethodConfigOperate().updateMockSwitchByClazz(clazzName,getSwitch(mark));
        return "redirect:umock";
    }




}
